package clas.ac.cn.common.config;

import clas.ac.cn.common.exception.IException;
import clas.ac.cn.common.vo.BootSpecificWord;
import clas.ac.cn.common.vo.CommonResponse;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.Map;

/**
 * Boot遇到错误过后返回JSON会使用这个类的这个方法进行数据得组织，在这里定义返回的数据
 * @author zhangzhang
 */
@Component
@Slf4j
public class IErrorAttributes extends DefaultErrorAttributes {

//    @Override
//    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
////        //调用父类的方法，会自动获取内置的那些属性
//        Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);
//        log.error("请求:"+webRequest.getContextPath()+"url=>{}"+JSON.toJSONString(errorAttributes));
//        return JSON.parseObject(JSON.toJSONString(  new CommonResponse<>(new IException(errorAttributes.get(BootSpecificWord.ERROR_RESPONSE_WORD).toString()))));
//    }

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options);
        log.error("请求出错=>{}:"+webRequest.getContextPath()+"url=>{}"+JSON.toJSONString(errorAttributes));
        return JSON.parseObject(JSON.toJSONString(  new CommonResponse<>(new IException(errorAttributes.get(BootSpecificWord.ERROR_RESPONSE_WORD).toString()))));
    }
}